package com.example.demo.ai.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.ai.uploadImage.DouBaoARKClient;
import com.example.ai.uploadImage.QiniuAIClient;
import com.example.demo.ai.entity.ImageGenerationResponse;
import com.example.demo.ai.entity.Message;
import com.example.demo.ai.entity.ResultData;
import com.example.demo.util.result.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@RestController
public class AiController {
    private static String taskID;
    private static List<String> urlList =  new ArrayList<>();

    @PostMapping("/api/generate")
    public Result<?> generate(@RequestBody Message message) {
        try {
            QiniuAIClient aiClient = new QiniuAIClient();
            List<Message> messages = new ArrayList<>();
            taskID = UUID.randomUUID().toString(); //更新任务
            urlList.clear();

            //基础提示词
            String baseContent = "请为以下小说按照漫画分镜和气泡，保持原文对话和叙述的顺序和内容不变，" +
                    "漫画中的角色不要出现明显歧义的情况（比如分镜1中，A是黄头发，到分镜B变成了紫头发），" +
                    "回答的格式按照场景1、场景2等等为标题划分，" +
                    "如果场景中分镜过多可以按每个场景对应一张漫画的内容量为维度再细分," +
                    "尽量控制每个场景对应3-6个分镜，如场景1有13个分镜此时不要去分成661而是平均一下分成445";
            messages.add(new Message("user", baseContent+"：["+message.getContent()+"]"));
            Map<String, String> scenes = aiClient.streamChatCompletion(messages);

            if(CollectionUtils.isNotEmpty(scenes)){
                DouBaoARKClient arkClient = new DouBaoARKClient();

                ResultData resultData = new ResultData();
                resultData.setCount(scenes.size());
                resultData.setTaskID(taskID);
                // 异步处理所有场景
                CompletableFuture.runAsync(() -> {
                    processRemainingScenes(scenes, arkClient, taskID);
                });

                // 立即处理第一个场景并返回
                for(Map.Entry<String, String> entry : scenes.entrySet()){
                    String basePrompt = "请为以下内容按照分镜和气泡，保持原文对话和叙述的顺序和内容不变生成相应的漫画," +
                            "日漫风格，线条清晰有力，阴影适中，色彩鲜明，对比度适中，场景自然流畅，保持角色服装、发型、特征一致。";
                    ImageGenerationResponse response = arkClient.generateImage(basePrompt+entry.getValue());
                    if (response.getData() != null && response.getData().length > 0) {
                        String imageUrl = response.getData()[0].getUrl();
                        urlList.add(imageUrl);
                        resultData.setUrlList(urlList);
                        return Result.ok(resultData);
                    }
                }
            }
            return Result.ok(scenes);
        } catch (Exception e) {
            return Result.error(e);
        }
    }

    @PostMapping("/api/nextPage")
    public Result<?> generate() {
//        List<String> messages = new ArrayList<>();
//        messages.add("https://ark-content-generation-v2-cn-beijing.tos-cn-beijing.volces.com/doubao-seedream-4-0/021761199506970dca48abe1b98965817cc24e2f18c9033a6fb29_0.jpeg?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTYWJkZTExNjA1ZDUyNDc3YzhjNTM5OGIyNjBhNDcyOTQ%2F20251023%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20251023T060530Z&X-Tos-Expires=86400&X-Tos-Signature=02c1a342a044a84fa61b1469f732f9bd6ef8bdef9654de28d48527a30b52973a&X-Tos-SignedHeaders=host");
//        messages.add("https://ark-content-generation-v2-cn-beijing.tos-cn-beijing.volces.com/doubao-seedream-4-0/021761205925989948899102b190db95f26e6101c9edea6c26a72_0.jpeg?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTYWJkZTExNjA1ZDUyNDc3YzhjNTM5OGIyNjBhNDcyOTQ%2F20251023%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20251023T075226Z&X-Tos-Expires=86400&X-Tos-Signature=4d92e2a50228fe6cd29a58d51616aff6eec1b74b5dd3181677af2104ff5d4a05&X-Tos-SignedHeaders=host");
//        return Result.ok(messages);
        return Result.ok(urlList);
    }

    // 异步处理剩余场景的方法
    private void processRemainingScenes(Map<String, String> scenes, DouBaoARKClient arkClient, String taskID) {
        boolean first = true;
        for (Map.Entry<String, String> entry : scenes.entrySet()) {
            if (first) {
                first = false; // 跳过第一个（已经在主线程处理）
                continue;
            }

            try {
                ImageGenerationResponse response = arkClient.generateImage(entry.getValue());
                if(!taskID.equals(AiController.taskID)){
                    return;
                }
                if (response.getData() != null && response.getData().length > 0) {
                    String imageUrl = response.getData()[0].getUrl();
                    // 这里可以存储到数据库、发送WebSocket通知等
                    urlList.add(imageUrl);
                    System.out.println("异步生成图片: " + entry.getKey() + " - " + imageUrl);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
